package com.example.summer_pro.controller;

import com.alibaba.fastjson.JSON;
import com.example.summer_pro.common.ContentData;
import com.example.summer_pro.common.Respond;
import com.example.summer_pro.common.ResultData;
import com.example.summer_pro.common.uidData;
import com.example.summer_pro.dao.QuesDao;
import com.example.summer_pro.entity.*;
import com.example.summer_pro.service.ContentService;
import com.example.summer_pro.service.Impl.NormalServiceImpl;
import com.example.summer_pro.service.Impl.QuesServiceImpl;
import com.example.summer_pro.service.NormalService;
import com.example.summer_pro.service.QuesService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.ParameterScriptAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import javax.websocket.SessionException;
import java.nio.charset.StandardCharsets;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class ContentController {
    @Autowired
    private QuesService quesService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private NormalService normalService;
    @Autowired
    private QuesDao quesDao;


        @PostMapping("/spiner")
        public Map<String,Object> test(@RequestBody ContentData contentData) throws JSONException, IOException {
            System.out.println(contentData.toString());
            Map<String, Object> map = new HashMap<>();
            map.put("data", contentData);

            System.out.println(JSON.toJSONString(contentData));
            System.out.println(JSON.parseObject(JSON.toJSONString(contentData), ContentData.class));
            System.out.println(JSON.parseObject(JSON.toJSONString(contentData), ContentData.class).getTitle());
            return map;

        }


    @PostMapping("/addContent")
    public Map<String,Object> addContent(@RequestBody ContentData contentData, HttpServletRequest request){

        HttpSession session = request.getSession();
        Integer u_id= (Integer) session.getAttribute("u_id");
        //暂时无法获取u_id
        if(u_id==null)
            u_id=1;
        System.out.println(u_id);
        Map<String,Object> map=new HashMap<>();

        Integer q_id= contentData.getQ_id();
        String q_type = quesService.getQuesByQid(q_id).getQ_type();
        contentData.setQ_type(q_type);
        Integer state = quesService.getQuesByQid(q_id).getState();
        contentData.setState(state);
        contentService.deleteAllContent(q_id,u_id);
        contentService.deleteJson(q_id,u_id);
        //System.out.println("x");
        Integer t_id;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date();
        String time = "";
        time = formatter.format(date);
        Integer t_num;
        String t_type="";

        String content="";
        String check="";
        Integer value=0;
        Integer sum_score=0;
        Integer number=0;

        for(int i=0;i<contentData.getQuestions().size();i++)
        {
            System.out.println("works");

            String answer="";
            String score="";
            String answer_user="";
            content="";
            check="";
            value=0;
            t_id=i;
            t_type=contentData.getQuestions().get(i).getType();
            //考试类型的问卷
            if(q_type.equals("考试问卷")){
                answer = contentData.getQuestions().get(i).getAnswer();
                score = contentData.getQuestions().get(i).getScore();
            }
            //投票问卷



            //填空题
            if(t_type.equals("textarea")){
                content = contentData.getQuestions().get(i).getInput();
            }
            //单选题+多选题
            else if(t_type.equals("radio")||t_type.equals("checkbox")){
                int ops=contentData.getQuestions().get(i).getOptions().size();
                for(int j=0;j<ops;j++){
                    if(contentData.getQuestions().get(i).getOptions().get(j).isChecked()){
                        check = check + contentData.getQuestions().get(i).getOptions().get(j).getKey()+"-";
                        answer_user = answer_user+contentData.getQuestions().get(i).getOptions().get(j).getKey();
                    }
                }
                if(answer_user.equals(answer)){
                    sum_score = sum_score + Integer.parseInt(score);
                }
            }
            //评分题
            else if(t_type.equals("grade")){
                int ops=contentData.getQuestions().get(i).getOptions().size();
                for(int j=0;j<ops;j++){
                    if(contentData.getQuestions().get(i).getOptions().get(j).isChecked()){
                        value = contentData.getQuestions().get(i).getOptions().get(j).getGrade();
                        number = j;
                        break;
                    }
                }
            }
            //报名问卷
            if(q_type.equals("报名问卷")){
                Normal normal = normalService.selectNormal(q_id,t_id);
                int m = 0;
                for(int j=0;j<normal.getNum_options();j++){
                    m=0;
                    Integer limit_number = contentData.getQuestions().get(i).getOptions().get(j).getLimit_number();
                    Integer remain_number = contentData.getQuestions().get(i).getOptions().get(j).getRemain_number();
                    List<Content> contentList = contentService.selectResult(q_id,t_id);
                    if(contentList == null){
                        ;
                    }else {
                        for(int k=0;k<contentList.size();k++){
                            String[] ss = contentList.get(k).getCheck_result().split("-");
                            for(int l=0;l<ss.length;l++){
                                if(Integer.parseInt(ss[l])==j){
                                    m++;
                                }
                            }
                        }
                    }
                    if(m<limit_number){
                        remain_number = limit_number-m-1;
                        contentData.getQuestions().get(i).getOptions().get(j).setRemain_number(remain_number);
                    }else {
                        map.put("success",false);
                        return map;
                    }
                }
            }
//
//            if(q_type.equals("报名问卷"))
//                for(int l=0;l<contentData.getQuestions().get(i).getLimit_number().size();l++){
//                   if(contentData.getQuestions().get(i).getRemain_number().get(l)<0){
//                         return new Respond(false,"error",contentData);
//                   }
//               }
            System.out.println("xxxxx"+number);
            Content content1=new Content(u_id,t_id,q_id,q_type,time,t_type,answer,score,sum_score,check,content,value,number);
            contentService.addNewContent(content1);
            Ques ques = quesDao.selectById(q_id);
            ques.setRecover_num(ques.getRecover_num()+1);
            quesDao.updateById(ques);
        }
        String strJson= JSON.toJSONString(contentData);
        contentService.addJson(q_id,u_id,strJson);
        map.put("data",contentData);
        map.put("state",quesService.getQuesByQid(q_id).getState());
        return map;
    }

    @PostMapping("/getContent")
    public Map<String, Object> getContent(@RequestBody Map<String,Integer> remap, HttpServletRequest request){
        HttpSession session = request.getSession();
        Integer u_id= (Integer) session.getAttribute("u_id");
        System.out.println("u_id"+u_id);
        Integer q_id= remap.get("q_id");
        Map<String,Object> map=new HashMap<>();
        int state=quesService.getQuesByQid(q_id).getState();
        map.put("state",state);
        //System.out.println("u_id"+u_id);
        try{
            ContentJSON contentJSON = contentService.selectJson(q_id, u_id);
            if (contentJSON == null) {
                NormalsJSON normalsJSON = normalService.selectJson(q_id);
                if (normalsJSON == null) {
                    map.put("data", "the questionnaire not build");

                } else {
                    map.put("data", normalsJSON.getJson());
                    System.out.println(normalsJSON.getJson());
                }
            }
            //System.out.println("json:"+contentService.selectJson(q_id,u_id));
            else {
                map.put("data", contentJSON.getJson());
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "失败");
        }
        return map;
    }

    @PostMapping("/getUid")
    public Map<String, Object> getUid(@RequestBody Map<String,Integer> remap){
        uidData uidData =new uidData();
        List<Integer> x=new ArrayList<>();
        Map<String, Object> map =new HashMap<>();
        Integer q_id = remap.get("q_id");
        Integer t_id = 0;
        List<Content> contentList = contentService.selectResult(q_id,t_id);
        if(contentList==null) {
            map.put("message", "content not exist");
        }
        else {
            for(int i=0;i<contentList.size();i++){
                x.add(contentList.get(i).getU_id());
            }
            uidData.setUid_list(x);
            map.put("data",uidData);
        }
        return map;
    }

    //查看一份问卷
    @PostMapping("/getContentByUid")
    public Map<String, Object> getContentByUid(@RequestBody Map<String,Integer> remap){
        Integer u_id= remap.get("u_id");
        Integer q_id= remap.get("q_id");
        Map<String,Object> map=new HashMap<>();
        ContentJSON contentJSON = contentService.selectJson(q_id,u_id);
        if(contentJSON==null){
            map.put("message","not founded");
        }else {
            map.put("data",contentJSON.getJson());
        }
        return map;
    }

    //查看每道题的统计结果
    @PostMapping("/showResults")
    public Map<String, Object> showResults(@RequestBody Map<String,Integer> remap){

        Integer q_id = remap.get("q_id");
        Integer t_id = remap.get("t_id");

        Map<String, Object> map = new HashMap<>();

        try {
            List<Content> contentList = contentService.selectResult(q_id,t_id);
            if(contentList==null) {
                    map.put("message", "content not exist");
            }
            else {
                double score = 0.0;
                int times = 0;

                ResultData resultData = new ResultData();
                Normal normal = normalService.selectNormal(q_id,t_id);
                if(normal==null){
                    map.put("message", "normal not exist");
                }
                else {
                    if(normal.getNum_options()==null){
                        map.put("message","num_options");
                    }
                    int x = normal.getNum_options();
                    //String[] grades = normal.getGrades().split("-");
                    List<Integer> list =new ArrayList<>();
                    resultData.setValue(list);
                    List<Integer> list1 =new ArrayList<>();
                    resultData.setOption(list1);
                    List<ResultData.Textarea> list2 = new ArrayList<>();
                    //resultData.setTextarea(list2);
                    //List<Integer> list3 = new ArrayList<>();
                    for(int j=0;j<x;j++) {
                        resultData.getValue().add(0);
                        resultData.getOption().add(0);
                        //list3.add(Integer.parseInt(grades[j]));
                    }
                    for(int i=0;i<contentList.size();i++){
                        ResultData.Textarea textarea = new ResultData.Textarea();
                        if(contentList.get(i).getType().equals("textarea")){
                            if(contentList.get(i).getU_id()==null){
                                map.put("message", "uid not filled");
                            }else {
                                Integer uid = contentList.get(i).getU_id();
                                textarea.setU_id(uid);
                            }
                            if(contentList.get(i).getTime()==null){
                                map.put("message", "time not filled");
                            }
                            else {
                                String time = contentList.get(i).getTime();
                                textarea.setTime(time);
                            }
                            if(contentList.get(i).getContent()==null){
                                map.put("message", "text not filled");
                            }else {
                                String str = contentList.get(i).getContent();
                                System.out.println("str:"+str);
                                textarea.setText(str);
                                list2.add(textarea);
                                System.out.println(list2.size());
//                                System.out.println(JSON.toJSONString(textarea));
//                                if(i!=contentList.size()-1){
//                                    map.put("data",JSON.toJSONString(resultData));
//                                }
                            }
                        }
                        else if(contentList.get(i).getType().equals("grade")){

                                if(contentList.get(i).getValue()==null){
                                    //System.out.println("x");
                                    map.put("message", "grade not filled");
                                }else {
                                    int m = resultData.getValue().get(contentList.get(i).getNumber());
                                    //System.out.println(contentList.get(i).getNumber());
                                    resultData.getValue().set(contentList.get(i).getNumber(),m+1);
                                    //System.out.println(contentList.get(j).getValue());
                                    score=score+contentList.get(i).getValue();
                                    times++;
                                }
                        }
                        else {
                            if(contentList.get(i).getCheck_result()==null){
                                map.put("message","radio or checkbox not filled");
                            }
                            else {
                                String[] str = contentList.get(i).getCheck_result().split("-");
                                for(int j=0;j<str.length;j++){
                                    int m = resultData.getOption().get(Integer.parseInt(str[j]));
                                    resultData.getOption().set(Integer.parseInt(str[j]),m+1);
                                }
                            }
                        }
                    }
                    //System.out.println(score);
                    //System.out.println(times);
                    resultData.setAverage_value(score/times);
                    resultData.setTotal(contentList.size());
                    resultData.setTextarea(list2);
                    //System.out.println(JSON.toJSONString(resultData.getTextarea().get(0)));
                    //System.out.println(JSON.toJSONString(resultData.getTextarea().get(1)));
                    map.put("data",JSON.toJSONString(resultData));

                }
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
        }
        return map;
    }


}



